package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.NotNullException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;


    @Override
    public Integer addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        return clazzMapper.addClazz(clazz);
    }

    @Override
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }

    @Override
    public PageResult page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        List<Clazz> clazzList = clazzMapper.page(clazzQueryParam);
        if (clazzList != null) {
            clazzList.forEach(clazz -> {
                LocalDate Date = LocalDate.parse(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                if (clazz.getBeginDate().isAfter(Date)) {
                    clazz.setStatus("未开班");
                } else if (clazz.getEndDate().isBefore(Date)) {
                    clazz.setStatus("已结课");
                } else {
                    clazz.setStatus("已开班");
                }
            });
        }
        Page<Clazz> clazzPage = (Page<Clazz>) clazzList;
        PageResult pageResult = new PageResult(clazzPage.getTotal(), clazzList);
        return pageResult;
    }

    @Override
    public Integer deleteById(Integer id) {
        Integer count = clazzMapper.deleteById(id);
        if (count == 0) {
            throw new NotNullException("对不起，当前班级下有学生，不能直接删除！");
        }
        return count;
    }

    @Override
    public Clazz selectById(Integer id) {
        return clazzMapper.selectById(id);
    }

    @Override
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazz(clazz);
    }
}
